{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Uh89IAIRrErD"
   },
   "source": [
    "# 机器翻译\n",
    "\n",
    "机器翻译是指将一段文本从一种语言自动翻译到另一种语言。因为一段文本序列在不同语言中的长度不一定相同，所以我们使用机器翻译为例来介绍编码器—解码器和注意力机制的应用。\n",
    "\n",
    "## 读取和预处理数据\n",
    "\n",
    "我们先定义一些特殊符号。其中“&lt;pad&gt;”（padding）符号用来添加在较短序列后，直到每个序列等长，而“&lt;bos&gt;”和“&lt;eos&gt;”符号分别表示序列的开始和结束。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "CYR481VbrErF"
   },
   "outputs": [],
   "source": [
    "import collections\n",
    "import io\n",
    "import math\n",
    "import d2ltorch as d2lt\n",
    "import torch\n",
    "from torch import nn, optim\n",
    "from torch.utils import data as tdata\n",
    "import torchtext as text\n",
    "\n",
    "PAD, BOS, EOS = '<pad>', '<bos>', '<eos>'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "DNLYTXQ_rErI"
   },
   "source": [
    "接着定义两个辅助函数对后面读取的数据进行预处理。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "U_RLIHh9rErJ"
   },
   "outputs": [],
   "source": [
    "# 将一个序列中所有的词记录在all_tokens中以便之后构造词典，然后在该序列后面添加PAD直到序列\n",
    "# 长度变为max_seq_len，然后将序列保存在all_seqs中\n",
    "def process_one_seq(seq_tokens, all_tokens, all_seqs, max_seq_len):\n",
    "    all_tokens.extend(seq_tokens)\n",
    "    seq_tokens += [EOS] + [PAD] * (max_seq_len - len(seq_tokens) - 1)\n",
    "    all_seqs.append(seq_tokens)\n",
    "\n",
    "# 使用所有的词来构造词典。并将所有序列中的词变换为词索引后构造Tensor实例\n",
    "def build_data(all_tokens, all_seqs):\n",
    "    vocab = text.vocab.Vocab(collections.Counter(all_tokens),\n",
    "                                  specials=[PAD, BOS, EOS])\n",
    "    indices = []\n",
    "    for seq in all_seqs:\n",
    "        indices.append([vocab.stoi[w] for w in seq])\n",
    "    return vocab, torch.tensor(indices)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "sdzeUzWArErL"
   },
   "source": [
    "为了演示方便，我们在这里使用一个很小的法语—英语数据集。在这个数据集里，每一行是一对法语句子和它对应的英语句子，中间使用`'\\t'`隔开。在读取数据时，我们在句末附上“&lt;eos&gt;”符号，并可能通过添加“&lt;pad&gt;”符号使每个序列的长度均为`max_seq_len`。我们为法语词和英语词分别创建词典。法语词的索引和英语词的索引相互独立。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "31"
    },
    "colab": {},
    "colab_type": "code",
    "id": "68n1WEiWrErL"
   },
   "outputs": [],
   "source": [
    "def read_data(max_seq_len):\n",
    "    # in和out分别是input和output的缩写\n",
    "    in_tokens, out_tokens, in_seqs, out_seqs = [], [], [], []\n",
    "    with io.open('../data/fr-en-small.txt') as f:\n",
    "        lines = f.readlines()\n",
    "    for line in lines:\n",
    "        in_seq, out_seq = line.rstrip().split('\\t')\n",
    "        in_seq_tokens, out_seq_tokens = in_seq.split(' '), out_seq.split(' ')\n",
    "        if max(len(in_seq_tokens), len(out_seq_tokens)) > max_seq_len - 1:\n",
    "            continue  # 如果加上EOS后长于max_seq_len，则忽略掉此样本\n",
    "        process_one_seq(in_seq_tokens, in_tokens, in_seqs, max_seq_len)\n",
    "        process_one_seq(out_seq_tokens, out_tokens, out_seqs, max_seq_len)\n",
    "    in_vocab, in_data = build_data(in_tokens, in_seqs)\n",
    "    out_vocab, out_data = build_data(out_tokens, out_seqs)\n",
    "    return in_vocab, out_vocab, tdata.TensorDataset(in_data, out_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "3x4Uj3terErO"
   },
   "source": [
    "将序列的最大长度设成7，然后查看读取到的第一个样本。该样本分别包含法语词索引序列和英语词索引序列。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "181"
    },
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "qx2dE0uRrErO",
    "outputId": "91764169-7687-43fa-ec15-688de551a547"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([ 5,  4, 45,  3,  2,  0,  0]), tensor([ 8,  4, 27,  3,  2,  0,  0]))"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max_seq_len = 7\n",
    "in_vocab, out_vocab, dataset = read_data(max_seq_len)\n",
    "dataset[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "LxGaKKLRrErR"
   },
   "source": [
    "## 含注意力机制的编码器—解码器\n",
    "\n",
    "我们将使用含注意力机制的编码器—解码器来将一段简短的法语翻译成英语。下面我们来介绍模型的实现。\n",
    "\n",
    "### 编码器\n",
    "\n",
    "在编码器中，我们将输入语言的词索引通过词嵌入层得到词的表征，然后输入到一个多层门控循环单元中。正如我们在[“循环神经网络的简洁实现”](../chapter_recurrent-neural-networks/rnn-nn.ipynb)一节提到的，PyTorch的`nn.GRU`实例在前向计算后也会分别返回输出和最终时间步的多层隐藏状态。其中的输出指的是最后一层的隐藏层在各个时间步的隐藏状态，并不涉及输出层计算。注意力机制将这些输出作为键项和值项。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "165"
    },
    "colab": {},
    "colab_type": "code",
    "id": "2AIW56JLrErS"
   },
   "outputs": [],
   "source": [
    "class Encoder(nn.Module):\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n",
    "                 drop_prob=0, **kwargs):\n",
    "        super(Encoder, self).__init__(**kwargs)\n",
    "        self.embedding = nn.Embedding(vocab_size, embed_size)\n",
    "        self.rnn = nn.GRU(embed_size, num_hiddens, num_layers, dropout=drop_prob)\n",
    "\n",
    "    def forward(self, inputs, state):\n",
    "        # 输入形状是(批量大小, 时间步数)。将输出互换样本维和时间步维\n",
    "        embedding = self.embedding(inputs.long()).permute(1, 0, 2)\n",
    "        return self.rnn(embedding, state)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "eqtf0jmcrErV"
   },
   "source": [
    "下面我们来创建一个批量大小为4、时间步数为7的小批量序列输入。设门控循环单元的隐藏层个数为2，隐藏单元个数为16。编码器对该输入执行前向计算后返回的输出形状为(时间步数, 批量大小, 隐藏单元个数)。门控循环单元在最终时间步的多层隐藏状态的形状为(隐藏层个数, 批量大小, 隐藏单元个数)。对于门控循环单元来说，`state`即隐藏状态；如果使用长短期记忆，`state`会是一个元组，除隐藏状态外还将包含另一个元素，即记忆细胞。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "166"
    },
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "4r-D8vUfrErV",
    "outputId": "bedd9a6b-b5f9-4773-f627-d6863f7d2117"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(torch.Size([7, 4, 16]), torch.Size([2, 4, 16]))"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "encoder = Encoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)\n",
    "output, state = encoder(torch.zeros(4, 7), None)\n",
    "output.shape, state.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "vc67BZARrErZ"
   },
   "source": [
    "### 注意力机制\n",
    "\n",
    "我们将实现[“注意力机制”](./attention.ipynb)一节中定义的函数$a$：将输入连结后通过含单隐藏层的多层感知机变换。其中隐藏层的输入是解码器的隐藏状态与编码器在所有时间步上隐藏状态的一一连结，且使用tanh函数作为激活函数。输出层的输出个数为1。两个`Linear`实例均不使用偏差。其中函数$a$定义里向量$\\boldsymbol{v}$的长度是一个超参数，即`attention_size`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "EFM809P5rEra"
   },
   "outputs": [],
   "source": [
    "def attention_model(input_size, attention_size):\n",
    "    model = nn.Sequential(\n",
    "        nn.Linear(input_size, attention_size, bias=False), \n",
    "        nn.Tanh(),\n",
    "        nn.Linear(attention_size, 1, bias=False)\n",
    "    )\n",
    "    return model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "f8ZpTLYlrErc"
   },
   "source": [
    "注意力机制的输入包括查询项、键项和值项。设编码器和解码器的隐藏单元个数相同。这里的查询项为解码器在上一时间步的隐藏状态，形状为(批量大小, 隐藏单元个数)；键项和值项均为编码器在所有时间步的隐藏状态，形状为(时间步数, 批量大小, 隐藏单元个数)。注意力机制返回当前时间步的背景变量，形状为(批量大小, 隐藏单元个数)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "h7K9CLZsrErc"
   },
   "outputs": [],
   "source": [
    "def attention_forward(model, enc_states, dec_state):\n",
    "    # 将解码器隐藏状态广播到和编码器隐藏状态形状相同后进行连结\n",
    "    dec_states = dec_state.unsqueeze(0).expand_as(enc_states)\n",
    "    enc_and_dec_states = torch.cat([enc_states, dec_states], dim=2)\n",
    "    e = model(enc_and_dec_states)  # 形状为(时间步数, 批量大小, 1)\n",
    "    alpha = torch.softmax(e, dim=0)  # 在时间步维度做softmax运算\n",
    "    return (alpha * enc_states).sum(dim=0)  # 返回背景变量"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "YPwc2JKNrEre"
   },
   "source": [
    "在下面的例子中，编码器的时间步数为10，批量大小为4，编码器和解码器的隐藏单元个数均为8。注意力机制返回一个小批量的背景向量，每个背景向量的长度等于编码器的隐藏单元个数。因此输出的形状为(4, 8)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "5Tbv7pIyrErf",
    "outputId": "b9e1d7f5-3c6c-4c15-a846-d043a4404fcd"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([4, 8])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "seq_len, batch_size, num_hiddens = 10, 4, 8\n",
    "model = attention_model(2 * num_hiddens, 10)\n",
    "enc_states = torch.zeros(seq_len, batch_size, num_hiddens)\n",
    "dec_state = torch.zeros(batch_size, num_hiddens)\n",
    "attention_forward(model, enc_states, dec_state).shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "JPS8YbGWrEri"
   },
   "source": [
    "### 含注意力机制的解码器\n",
    "\n",
    "我们直接将编码器在最终时间步的隐藏状态作为解码器的初始隐藏状态。这要求编码器和解码器的循环神经网络使用相同的隐藏层个数和隐藏单元个数。\n",
    "\n",
    "在解码器的前向计算中，我们先通过刚刚介绍的注意力机制计算得到当前时间步的背景向量。由于解码器的输入来自输出语言的词索引，我们将输入通过词嵌入层得到表征，然后和背景向量在特征维连结。我们将连结后的结果与上一时间步的隐藏状态通过门控循环单元计算出当前时间步的输出与隐藏状态。最后，我们将输出通过全连接层变换为有关各个输出词的预测，形状为(批量大小, 输出词典大小)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "170"
    },
    "colab": {},
    "colab_type": "code",
    "id": "RfQvECkGrEri"
   },
   "outputs": [],
   "source": [
    "class Decoder(nn.Module):\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n",
    "                 attention_size, drop_prob=0, **kwargs):\n",
    "        super(Decoder, self).__init__(**kwargs)\n",
    "        self.embedding = nn.Embedding(vocab_size, embed_size)\n",
    "        self.attention = attention_model(2 * num_hiddens, attention_size)\n",
    "        self.rnn = nn.GRU(embed_size + num_hiddens, num_hiddens, num_layers, dropout=drop_prob)\n",
    "        self.out = nn.Linear(num_hiddens, vocab_size)\n",
    "\n",
    "    def forward(self, cur_input, state, enc_states):\n",
    "        # 使用注意力机制计算背景向量，形状为(批量大小, 隐藏单元个数)\n",
    "        c = attention_forward(self.attention, enc_states, state[-1])\n",
    "        # 将嵌入后的输入和背景向量在特征维连结\n",
    "        input_and_c = torch.cat([self.embedding(cur_input), c], dim=1)\n",
    "        # 为输入和背景向量的连结增加时间步维，时间步个数为1\n",
    "        output, state = self.rnn(input_and_c.unsqueeze(0), state)\n",
    "        # 移除时间步维，输出形状为(批量大小, 输出词典大小)\n",
    "        output = self.out(output).squeeze(dim=0)\n",
    "        return output, state\n",
    "\n",
    "    def begin_state(self, enc_state):\n",
    "        # 直接将编码器最终时间步的隐藏状态作为解码器的初始隐藏状态\n",
    "        return enc_state"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "WCaBAq3UrErk"
   },
   "source": [
    "## 训练模型\n",
    "\n",
    "我们先实现`batch_loss`函数计算一个小批量的损失。解码器在最初时间步的输入是特殊字符`BOS`。之后，解码器在某时间步的输入为样本输出序列在上一时间步的词，即强制教学。此外，同[“word2vec的实现”](word2vec-nn.ipynb)一节中的实现一样，我们在这里也使用掩码变量避免填充项对损失函数计算的影响。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "ip4_psGLrErl"
   },
   "outputs": [],
   "source": [
    "def batch_loss(encoder, decoder, X, Y, loss):\n",
    "    batch_size = X.shape[0]\n",
    "    enc_state = None\n",
    "    enc_outputs, enc_state = encoder(X, enc_state)\n",
    "    # 初始化解码器的隐藏状态\n",
    "    dec_state = decoder.begin_state(enc_state)\n",
    "    # 解码器在最初时间步的输入是BOS\n",
    "    dec_input = torch.tensor([out_vocab.stoi[BOS]] * batch_size)\n",
    "    # 我们将使用掩码变量mask来忽略掉标签为填充项PAD的损失\n",
    "    mask, num_not_pad_tokens = torch.ones(batch_size), 0\n",
    "    l = torch.tensor([0], dtype=torch.float)\n",
    "    for y in Y.t():\n",
    "        dec_output, dec_state = decoder(dec_input, dec_state, enc_outputs)\n",
    "        l = l + (mask * loss(dec_output, y)).sum()\n",
    "        dec_input = y  # 使用强制教学\n",
    "        num_not_pad_tokens += mask.sum().item()\n",
    "        # 当遇到EOS时，序列后面的词将均为PAD，相应位置的掩码设成0\n",
    "        mask = mask * (y != out_vocab.stoi[EOS]).float()\n",
    "    return l / num_not_pad_tokens"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "PaQWLh0ZrErn"
   },
   "source": [
    "在训练函数中，我们需要同时迭代编码器和解码器的模型参数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "188"
    },
    "colab": {},
    "colab_type": "code",
    "id": "b89VX-8brErn"
   },
   "outputs": [],
   "source": [
    "def train(encoder, decoder, dataset, lr, batch_size, num_epochs):\n",
    "    d2lt.params_init(encoder, init=nn.init.xavier_uniform_)\n",
    "    d2lt.params_init(decoder, init=nn.init.xavier_uniform_)\n",
    "\n",
    "    enc_optimizer = optim.Adam(encoder.parameters(), lr=lr)\n",
    "    dec_optimizer = optim.Adam(decoder.parameters(), lr=lr)\n",
    "    loss = nn.CrossEntropyLoss(reduction='none')\n",
    "    data_iter = tdata.DataLoader(dataset, batch_size, shuffle=True)\n",
    "    for epoch in range(num_epochs):\n",
    "        l_sum = 0.0\n",
    "        for X, Y in data_iter:\n",
    "            enc_optimizer.zero_grad()\n",
    "            dec_optimizer.zero_grad()\n",
    "            l = batch_loss(encoder, decoder, X, Y, loss)\n",
    "            l.backward()\n",
    "            enc_optimizer.step()\n",
    "            dec_optimizer.step()\n",
    "            l_sum += l.item()\n",
    "        if (epoch + 1) % 10 == 0:\n",
    "            print(\"epoch %d, loss %.3f\" % (epoch + 1, l_sum / len(data_iter)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "lme39h6frErq"
   },
   "source": [
    "接下来，创建模型实例并设置超参数。然后，我们就可以训练模型了。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 107
    },
    "colab_type": "code",
    "id": "fC6TPgz4rErq",
    "outputId": "a5084f50-ee38-45fb-8256-4483fc9dd867"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, loss 0.558\n",
      "epoch 20, loss 0.258\n",
      "epoch 30, loss 0.205\n",
      "epoch 40, loss 0.080\n",
      "epoch 50, loss 0.143\n"
     ]
    }
   ],
   "source": [
    "embed_size, num_hiddens, num_layers = 64, 64, 2\n",
    "attention_size, drop_prob, lr, batch_size, num_epochs = 10, 0.5, 0.01, 2, 50\n",
    "encoder = Encoder(len(in_vocab), embed_size, num_hiddens, num_layers,\n",
    "                  drop_prob)\n",
    "decoder = Decoder(len(out_vocab), embed_size, num_hiddens, num_layers,\n",
    "                  attention_size, drop_prob)\n",
    "train(encoder, decoder, dataset, lr, batch_size, num_epochs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "1MoZo09orErz"
   },
   "source": [
    "## 预测不定长的序列\n",
    "\n",
    "在[“束搜索”](beam-search.ipynb)一节中我们介绍了3种方法来生成解码器在每个时间步的输出。这里我们实现最简单的贪婪搜索。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "177"
    },
    "colab": {},
    "colab_type": "code",
    "id": "MotBbHLsrEr0"
   },
   "outputs": [],
   "source": [
    "def translate(encoder, decoder, input_seq, max_seq_len):\n",
    "    with torch.no_grad():\n",
    "        in_tokens = input_seq.split(' ')\n",
    "        in_tokens += [EOS] + [PAD] * (max_seq_len - len(in_tokens) - 1)\n",
    "        enc_input = torch.tensor([[in_vocab.stoi[token] for token in in_tokens]])\n",
    "        enc_state = None\n",
    "        enc_output, enc_state = encoder(enc_input, enc_state)\n",
    "        dec_input = torch.tensor([out_vocab.stoi[BOS]])\n",
    "        dec_state = decoder.begin_state(enc_state)\n",
    "        output_tokens = []\n",
    "        for _ in range(max_seq_len):\n",
    "            dec_output, dec_state = decoder(dec_input, dec_state, enc_output)\n",
    "            pred = dec_output.argmax(dim=1)\n",
    "            pred_token = out_vocab.itos[int(pred.item())]\n",
    "            if pred_token == EOS:  # 当任一时间步搜索出EOS时，输出序列即完成\n",
    "                break\n",
    "            else:\n",
    "                output_tokens.append(pred_token)\n",
    "                dec_input = pred\n",
    "    return output_tokens"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "9EdimU4wrEr3"
   },
   "source": [
    "简单测试一下模型。输入法语句子“ils regardent.”，翻译后的英语句子应该是“they are watching.”。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "FRK7l2QAt30O",
    "outputId": "a9bcbf7b-d452-4841-b8a7-8003e1f4b348"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['they', 'are', 'watching', '.']"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "input_seq = 'ils regardent .'\n",
    "translate(encoder, decoder, input_seq, max_seq_len)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "i6uiXuz-rEr8"
   },
   "source": [
    "## 评价翻译结果\n",
    "\n",
    "评价机器翻译结果通常使用BLEU（Bilingual Evaluation Understudy）[1]。对于模型预测序列中任意的子序列，BLEU考察这个子序列是否出现在标签序列中。\n",
    "\n",
    "具体来说，设词数为$n$的子序列的精度为$p_n$。它是预测序列与标签序列匹配词数为$n$的子序列的数量与预测序列中词数为$n$的子序列的数量之比。举个例子，假设标签序列为$A$、$B$、$C$、$D$、$E$、$F$，预测序列为$A$、$B$、$B$、$C$、$D$，那么$p_1 = 4/5,\\ p_2 = 3/4,\\ p_3 = 1/3,\\ p_4 = 0$。设$len_{\\text{label}}$和$len_{\\text{pred}}$分别为标签序列和预测序列的词数，那么，BLEU的定义为\n",
    "\n",
    "$$ \\exp\\left(\\min\\left(0, 1 - \\frac{len_{\\text{label}}}{len_{\\text{pred}}}\\right)\\right) \\prod_{n=1}^k p_n^{1/2^n},$$\n",
    "\n",
    "其中$k$是我们希望匹配的子序列的最大词数。可以看到当预测序列和标签序列完全一致时，BLEU为1。\n",
    "\n",
    "因为匹配较长子序列比匹配较短子序列更难，BLEU对匹配较长子序列的精度赋予了更大权重。例如，当$p_n$固定在0.5时，随着$n$的增大，$0.5^{1/2} \\approx 0.7, 0.5^{1/4} \\approx 0.84, 0.5^{1/8} \\approx 0.92, 0.5^{1/16} \\approx 0.96$。另外，模型预测较短序列往往会得到较高$p_n$值。因此，上式中连乘项前面的系数是为了惩罚较短的输出而设的。举个例子，当$k=2$时，假设标签序列为$A$、$B$、$C$、$D$、$E$、$F$，而预测序列为$A$、$B$。虽然$p_1 = p_2 = 1$，但惩罚系数$\\exp(1-6/2) \\approx 0.14$，因此BLEU也接近0.14。\n",
    "\n",
    "下面来实现BLEU的计算。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "boudnrxuvOXR"
   },
   "outputs": [],
   "source": [
    "def bleu(pred_tokens, label_tokens, k):\n",
    "    len_pred, len_label = len(pred_tokens), len(label_tokens)\n",
    "    score = math.exp(min(0, 1 - len_label / len_pred))\n",
    "    for n in range(1, k + 1):\n",
    "        num_matches, label_subs = 0, collections.defaultdict(int)\n",
    "        for i in range(len_label - n + 1):\n",
    "            label_subs[''.join(label_tokens[i: i + n])] += 1\n",
    "        for i in range(len_pred - n + 1):\n",
    "            if label_subs[''.join(pred_tokens[i: i + n])] > 0:\n",
    "                num_matches += 1\n",
    "                label_subs[''.join(pred_tokens[i: i + n])] -= 1      \n",
    "        score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))\n",
    "    return score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ESvev2X3rEr-"
   },
   "source": [
    "接下来，定义一个辅助打印函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "E_8Ar_RDrEr_"
   },
   "outputs": [],
   "source": [
    "def score(input_seq, label_seq, k):\n",
    "    pred_tokens = translate(encoder, decoder, input_seq, max_seq_len)\n",
    "    label_tokens = label_seq.split(' ')\n",
    "    print('bleu %.3f, predict: %s' % (bleu(pred_tokens, label_tokens, k),\n",
    "                                      ' '.join(pred_tokens)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "NonFzpZorEsB"
   },
   "source": [
    "预测正确则分数为1。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "--fg1bxLvaKL",
    "outputId": "6d49a163-1455-4d68-e760-beeed21cac07"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bleu 1.000, predict: they are watching .\n"
     ]
    }
   ],
   "source": [
    "score('ils regardent .', 'they are watching .', k=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "tpuJskTMrEsE"
   },
   "source": [
    "测试一个不在训练集中的样本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 35
    },
    "colab_type": "code",
    "id": "z21s3052vfsh",
    "outputId": "4318ee1c-9a3f-4cd6-df35-c396386a6c26"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bleu 0.658, predict: they are russian .\n"
     ]
    }
   ],
   "source": [
    "score('ils sont canadiens .', 'they are canadian .', k=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "isISI9gerEsH"
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 可以将编码器—解码器和注意力机制应用于机器翻译中。\n",
    "* BLEU可以用来评价翻译结果。\n",
    "\n",
    "## 练习\n",
    "\n",
    "* 如果编码器和解码器的隐藏单元个数不同或隐藏层个数不同，该如何改进解码器的隐藏状态的初始化方法？\n",
    "* 在训练中，将强制教学替换为使用解码器在上一时间步的输出作为解码器在当前时间步的输入，结果有什么变化吗？\n",
    "* 试着使用更大的翻译数据集来训练模型，如WMT [2] 和Tatoeba Project [3]。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "## 参考文献\n",
    "\n",
    "[1] Papineni, K., Roukos, S., Ward, T., & Zhu, W. J. (2002, July). BLEU: a method for automatic evaluation of machine translation. In Proceedings of the 40th annual meeting on association for computational linguistics (pp. 311-318). Association for Computational Linguistics.\n",
    "\n",
    "[2] WMT. http://www.statmt.org/wmt14/translation-task.html\n",
    "\n",
    "[3] Tatoeba Project. http://www.manythings.org/anki/\n",
    "\n",
    "## 扫码直达[讨论区](https://discuss.gluon.ai/t/topic/4689)\n",
    "\n",
    "![](../img/qr_machine-translation.svg)"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "machine-translation.ipynb",
   "provenance": [],
   "version": "0.3.2"
  },
  "kernelspec": {
   "display_name": "Python [conda env:pytorch]",
   "language": "python",
   "name": "conda-env-pytorch-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
